<template>
    <!-- 选择规格卡片 -->
    <div class="specificationCard">
        <div class="title">
            <img :src="img" alt="">
            <div>
                <p>价格：￥{{ price }}</p>
                <div>
                    <p v-for="(value, key) in objSpecification" :key="key">
                        {{ value }}
                    </p>
                </div>
            </div>
        </div>

        <div class="content">
            <div v-for="(item, index) in specificationList" :key="index">
                <p>{{ item.name }}</p>
                <div class="val">
                    <p v-for="item1 in item.valueList" :key="item1.id" @click="choose(item1.value, item.name, item1.id)"
                        :class="item1.id == specification || item1.id == color ? 'chooseAction' : 'chooseInAction'">
                        {{ item1.value }}
                    </p>
                </div>
            </div>

            <div class="num">
                <p>数量</p>
                <van-stepper v-model="value" button-size="40rem" input-width="60rem" />
            </div>
        </div>
        <div class="homeShoppingCart">
            <van-action-bar>
                <van-action-bar-icon icon="star-o" text="收藏" />
                <van-action-bar-icon icon="cart-o" text="购物车" @click="toshoppingcar" />
                <van-action-bar-button type="warning" text="加入购物车" @click="shoppingCar" />
                <van-action-bar-button type="danger" :text="num == 0 ? '商品已售空' : '立即购买'" :disabled="num == 0 ? true : false"
                    :class="num == 0 ? 'shoppingStyle' : 'shoppingStyle1'" @click="goShopping" />
            </van-action-bar>
        </div>
    </div>
</template>

<script>
import { ref } from 'vue';
import { showToast } from 'vant';
import { service } from "../api/config";
export default {
    name: "detail",
    emits: ['updatetitle'],
    data() {
        return {
            id: "",
            num: 1,
            img: "",
            data: {},
            info: {},
            price: 0,
            color: 0,
            productList: [],
            specification: 0,
            specificationList: [],
            newArrSpecification: [],
            objSpecification: { "name": "请选择规格数量" },
            homeObjSpecification: { "name": "数量规格选择" },
            goodsId: 0
        }
    },
    setup() {
        const onClickLeft = () => history.back();
        const value = ref(1);
        return {
            onClickLeft,
            value,//商品购买数量
        };
    },
    mounted() {
        this.id = this.$store.state.goodsid;
        service.get("/wx/goods/detail", {
            params: {
                id: this.id
            }
        }).then(res => {
            this.data = res.data.data
            this.info = this.data.info
            this.productList = this.data.productList
            this.img = this.productList[0].url
            this.price = this.productList[0].price
            this.specificationList = this.data.specificationList
        });
    },
    methods: {
        choose(value, name, id) {
            if ('name' in this.objSpecification) {
                delete this.objSpecification['name']
            }
            if (name == "规格") {
                if (name in this.objSpecification) {
                    this.objSpecification[name] = value
                } else {
                    this.objSpecification = { [name]: value, ...this.objSpecification }
                }
                this.specification = id
            } else {
                this.objSpecification = { ...this.objSpecification, [name]: value }
                this.color = id
            }
            this.homeObjSpecification = this.objSpecification
            this.newArrSpecification = Object.values(this.objSpecification)
            function arraysEqual(a, b) {
                if (a === b) return true;
                if (a == null || b == null) return false;
                if (a.length != b.length) return false;
                return a.every((element, index) => element === b[index]);
            }
            var newInfo = this.productList.map(item => {
                const isBool = arraysEqual(this.newArrSpecification, item.specifications)
                if (isBool == true) {
                    return { price: item.price, img: item.url, num: item.number, id: item.id }
                }
            }).filter(item => {
                return item != undefined;
            })[0];
            //console.log(newInfo);
            if (newInfo != undefined) {
                this.goodsId = newInfo.id
                this.price = newInfo.price
                this.img = newInfo.img
                this.num = newInfo.num
            }
            this.$emit('updatetitle', Object.values(this.homeObjSpecification).join(','));
        },
        toshoppingcar() {
            this.$router.push("/ShoppingCart");
        },
        goShopping() {
            let a = 0;
            var specificationLength = Math.max(...this.newArrSpecification.map(item => {
                if (item !== "") {
                    a++;
                }
                return a
            }))
            if (specificationLength != this.specificationList.length) {
                showToast({
                    message: '请选择完整的规格',
                    icon: require("@/assets/images/sad.png"),
                });
            } else if (this.num < this.value) {
                showToast({
                    message: '选择的数量大于库存数量',
                    icon: require("@/assets/images/sad.png"),
                });
            } else {
                service.post("/wx/cart/fastadd", {
                    goodsId: this.$store.state.goodsid,
                    number: this.value,
                    productId: this.goodsId
                }).then(res => {
                    sessionStorage.setItem("mycartid", res.data.data)
                });
                const infoArr = [
                    {
                        name: this.info.name,
                        img: this.img,
                        num: this.value,
                        specification: this.newArrSpecification,
                        price: this.price,
                    }
                ];
                this.$store.commit("setValue", {
                    key: "tocar",
                    value: JSON.stringify(infoArr),
                });
                this.$router.push("/orderConfirm")

            }
        },
        shoppingCar() {
            let a = 0;
            let specificationLength = Math.max(...this.newArrSpecification.map(item => {
                if (item !== "") {
                    a++;
                }
                return a
            }))
            if (specificationLength != this.specificationList.length) {
                showToast({
                    message: '请选择完整的规格',
                    icon: require("@/assets/images/sad.png"),
                });
            } else if (this.num == 0) {
                showToast({
                    message: '没有库存',
                    icon: require("@/assets/images/sad.png"),
                });
            } else {
                service.post("/wx/cart/add", {
                    goodsId: this.$store.state.goodsid,
                    number: this.value,
                    productId: this.goodsId
                }).then(res => {
                    console.log(res);
                    if (res.data.errmsg == "成功") {
                        showToast({
                            message: '加入购物车成功',
                            icon: require("@/assets/images/对勾.png"),
                        });
                    } else {
                        showToast({
                            message: res.data.errmsg,
                            icon: require("@/assets/images/sad.png"),
                        });
                    }

                });

            }
        },
    }
};
</script>

<style scoped>
.specificationCard {
    border-top: #bdbdbd solid 1rem;
}

.specificationCard .van-cell {
    padding-left: 5rem;
}

.specificationCard .title {
    display: flex;
}

.specificationCard .title img {
    width: 25%;
    padding: 10rem;
}

.specificationCard .title>div>p {
    margin: 40rem 0 0rem;
}

.specificationCard .title div div {
    display: flex;
}

.specificationCard .title div div p {
    margin-right: 10rem;
}

.specificationCard .content {
    padding: 16rem 16rem 16rem;
}

.specificationCard .content .val {
    display: flex;
}

.specificationCard .content .val .chooseInAction {
    border: solid 1rem black;
    padding: 5rem 15rem;
    margin: 5rem 10rem 15rem 0;
    color: black;
}

.specificationCard .content .val .chooseAction {
    color: orangered;
    border: 1rem solid orangered;
    padding: 5rem 15rem;
    margin: 5rem 10rem 15rem 0;
}

.specificationCard .num {
    padding-bottom: 45rem;
}

.specificationCard .num p {
    margin-bottom: 5rem;
}
</style>